// 圣经问答游戏 - 降级音频系统

class FallbackAudioSystem {
    constructor() {
        this.enabled = true;
        this.volume = 0.5;
        this.audioElements = {};
        this.createAudioElements();
    }

    // 创建音频元素
    createAudioElements() {
        // 使用简单的音频数据URL创建音效
        this.audioElements = {
            correct: this.createAudioElement(this.generateTone(523, 0.3)), // C5音
            wrong: this.createAudioElement(this.generateTone(220, 0.4)),   // A3音
            achievement: this.createAudioElement(this.generateChord([262, 330, 392], 0.5)), // 和弦
            click: this.createAudioElement(this.generateTone(800, 0.1))    // 高音
        };
    }

    // 生成音调
    generateTone(frequency, duration) {
        const sampleRate = 22050;
        const samples = Math.floor(sampleRate * duration);
        const buffer = new ArrayBuffer(44 + samples * 2);
        const view = new DataView(buffer);
        
        // WAV文件头
        this.writeWAVHeader(view, samples, sampleRate);
        
        // 生成正弦波
        for (let i = 0; i < samples; i++) {
            const t = i / sampleRate;
            const sample = Math.sin(2 * Math.PI * frequency * t) * 0.3;
            // 添加淡入淡出效果
            const envelope = this.getEnvelope(i, samples);
            view.setInt16(44 + i * 2, sample * envelope * 32767, true);
        }
        
        return new Blob([buffer], { type: 'audio/wav' });
    }

    // 生成和弦
    generateChord(frequencies, duration) {
        const sampleRate = 22050;
        const samples = Math.floor(sampleRate * duration);
        const buffer = new ArrayBuffer(44 + samples * 2);
        const view = new DataView(buffer);
        
        this.writeWAVHeader(view, samples, sampleRate);
        
        for (let i = 0; i < samples; i++) {
            const t = i / sampleRate;
            let sample = 0;
            
            // 混合多个频率
            frequencies.forEach(freq => {
                sample += Math.sin(2 * Math.PI * freq * t) * (0.2 / frequencies.length);
            });
            
            const envelope = this.getEnvelope(i, samples);
            view.setInt16(44 + i * 2, sample * envelope * 32767, true);
        }
        
        return new Blob([buffer], { type: 'audio/wav' });
    }

    // 写入WAV文件头
    writeWAVHeader(view, samples, sampleRate) {
        const writeString = (offset, string) => {
            for (let i = 0; i < string.length; i++) {
                view.setUint8(offset + i, string.charCodeAt(i));
            }
        };
        
        writeString(0, 'RIFF');
        view.setUint32(4, 36 + samples * 2, true);
        writeString(8, 'WAVE');
        writeString(12, 'fmt ');
        view.setUint32(16, 16, true);
        view.setUint16(20, 1, true);
        view.setUint16(22, 1, true);
        view.setUint32(24, sampleRate, true);
        view.setUint32(28, sampleRate * 2, true);
        view.setUint16(32, 2, true);
        view.setUint16(34, 16, true);
        writeString(36, 'data');
        view.setUint32(40, samples * 2, true);
    }

    // 获取包络（淡入淡出）
    getEnvelope(sample, totalSamples) {
        const fadeIn = Math.min(sample / (totalSamples * 0.1), 1);
        const fadeOut = Math.min((totalSamples - sample) / (totalSamples * 0.1), 1);
        return Math.min(fadeIn, fadeOut);
    }

    // 创建音频元素
    createAudioElement(blob) {
        const audio = new Audio();
        audio.src = URL.createObjectURL(blob);
        audio.preload = 'auto';
        return audio;
    }

    // 播放音效
    playSound(soundName) {
        if (!this.enabled || !this.audioElements[soundName]) return;
        
        try {
            const audio = this.audioElements[soundName];
            audio.volume = this.volume;
            audio.currentTime = 0;
            
            // 创建播放Promise来处理自动播放策略
            const playPromise = audio.play();
            if (playPromise !== undefined) {
                playPromise.catch(error => {
                    console.log('音效播放被阻止:', error);
                    // 可以在这里添加用户交互后重试的逻辑
                });
            }
        } catch (error) {
            console.log('音效播放失败:', error);
        }
    }

    // 设置音量
    setVolume(volume) {
        this.volume = Math.max(0, Math.min(1, volume));
    }

    // 启用/禁用音效
    setEnabled(enabled) {
        this.enabled = enabled;
    }

    // 检查音频支持
    isSupported() {
        return !!window.Audio;
    }

    // 预加载音效（用户交互后调用）
    preloadSounds() {
        Object.values(this.audioElements).forEach(audio => {
            audio.load();
        });
    }

    // 用户交互后启用音频
    enableAudioAfterInteraction() {
        // 播放一个静音音频来启用音频上下文
        Object.values(this.audioElements).forEach(audio => {
            audio.volume = 0;
            const playPromise = audio.play();
            if (playPromise !== undefined) {
                playPromise.then(() => {
                    audio.pause();
                    audio.currentTime = 0;
                    audio.volume = this.volume;
                }).catch(() => {
                    // 忽略错误
                });
            }
        });
    }
}

// 创建全局音频系统实例
window.fallbackAudioSystem = new FallbackAudioSystem();

// 在用户首次交互时启用音频
document.addEventListener('click', function enableAudio() {
    if (window.fallbackAudioSystem) {
        fallbackAudioSystem.enableAudioAfterInteraction();
    }
    document.removeEventListener('click', enableAudio);
}, { once: true });